﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Wwtfly.BBS.BackBLL.Users;
using Wwtfly.BBS.BackModels.Models.Users;
using Wwtfly.Utility;
using Wwtfly.BBS.Enums.Users;
using System.Web.Configuration;
using System.Configuration;
using System.Web.Security;
using Wwtfly.Extensions;
using System.Web.SessionState;
using Wwtfly.BBS.BackModels.Models.Right;
using Wwtfly.BBS.BackBLL.Right;
using Wwtfly.BBS.BackBLL.ExpertNews;
using Wwtfly.BBS.BackModels.Models.ExpertNews;
using Wwtfly.BBS.BackBLL.Plays;
using Wwtfly.BBS.BackModels.Models.Plays;
namespace Wwtfly.BBS.ForeApplication.WebForm.ashx
{
    /// <summary>
    /// UsersHandler 的摘要说明
    /// </summary>
    public class UsersHandler : IHttpHandler,IRequiresSessionState
    {
        private HttpContext Context = null;
        private string keyMessage = string.Empty;
        private string keyError = string.Empty;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            context.Request.ContentEncoding = System.Text.Encoding.UTF8;
            Context = context;
            if (context.Request["parms"] != null)
            {
                try
                {
                    string parm = context.Request["parms"];
                    switch (parm)
                    {
                        case "Add_pmusers":  //注册
                            Add_pmusers();
                            break;
                        case "UserName_pmusers": //验证用户名
                            UserName_pmusers();
                            break;
                        case "login_pmusers":

                            login_pmusers();  //登陆
                            break;
                        case "ExpertNewAdd":
                            ExpertNewAdd();
                            break;
                        case"expertLooknews":
                            expertLooknews();//查看专题
                            break;
                        case "Update_userpwd":
                            Update_userpwd();//修改用户密码
                            break;

                    }
                }
                catch (Exception e)
                {
                    Context.Response.Write(e + "...请求超时！");
                }
            }
        }

        void Update_userpwd()
        {
            if (Context.Session[LoginUserUtil.LOGIN_USER] != null)
            {
                UsersModel user = Context.Session[LoginUserUtil.LOGIN_USER] as UsersModel;
                string pwdold = Context.Request.Params["pwdold"];
                if (pwdold.Equals(user.UserPassword))
                {
                    UsersModel userpwd = new UsersModel();
                    string newpwd = Context.Request.Params["newpwd"];
                    userpwd.UserPassword = newpwd;
                    userpwd.Id = user.Id;
                    bool bol = UsersBLL.UpdatePwd(userpwd);
                    if (bol)
                    {
                        Context.Response.Write("1");
                    }
                    else
                    {
                        Context.Response.Write("-2");
                    }
                }
                else
                {
                    Context.Response.Write("0");
                }
            }
            else
            {
                Context.Response.Write("-1");
            }
        }
        /// <summary>
        /// 查看专家信息
        /// </summary>
        void expertLooknews()
        {
            if (Context.Session[LoginUserUtil.LOGIN_USER] != null)
            {
                UsersModel user = (UsersModel)Context.Session[LoginUserUtil.LOGIN_USER];
                if (user.UserColourMoney < 1)
                {
                    Context.Response.Write("-1");
                }
                else
                {
                    int caibi = Convert.ToInt32(Context.Request.Params["CountMoney"].ToString());
                    int expertNewsId = Convert.ToInt32(Context.Request.Params["expertNewsId"].ToString());
                    int rult=ExpertNewsBLL.ExpertLookNewsExcut(user.Id, expertNewsId,Convert.ToInt32(user.UserColourMoney), caibi);

                    Context.Response.Write(rult.ToString());
                }
               
            }
            else
            {
                Context.Response.Write("3");
            }
        }
        void ExpertNewAdd()
        {
            if (Context.Session[LoginUserUtil.LOGIN_USER] != null)
            {
                UsersModel user =(UsersModel) Context.Session[LoginUserUtil.LOGIN_USER];
                string LotteryNos = HttpContext.Current.Request["LotteryNo"];//期号
                if (LotteryNos == "")
                {
                    Context.Response.Write("当前彩种期号不存在!");//当前彩种期号不存在

                }
                else
                {
                    if (user.Id != 0)
                    {
                        string newsContents = HttpContext.Current.Request.Form["newsContent"];//方案内容
                        string LotteryTypes = HttpContext.Current.Request["LotteryType"]; //彩种类型
                        int iLotteryType=Convert.ToInt32(LotteryTypes);
                        string newtitles = HttpContext.Current.Request["newtitle"];//方案标题
                        string newKeys = HttpContext.Current.Request["newKey"];
                        string Exmiaoshus = HttpContext.Current.Request["Exmiaoshu"];
                        string Selectnums = HttpContext.Current.Request["Selectnum"];//彩币
                        int nums = Convert.ToInt32(Selectnums);
                        string ExperRemarks = HttpContext.Current.Request["ExperRemark"];
                       PlaysShowsModel  palyshow= PlaysBLL.GetInfo(iLotteryType, LotteryNos);
                       if (palyshow.EndTime != null)
                       {

                           ExpertNewsShowsModel expernews = new ExpertNewsShowsModel();
                           expernews.UserId = user.Id;
                           expernews.PlayId = Convert.ToInt32(LotteryTypes);
                           expernews.PlayQiNo = LotteryNos;
                           expernews.CreateTime = System.DateTime.Now;
                           expernews.Extitle = newtitles;
                           expernews.Keyword = newKeys;
                           expernews.Exmiaoshu = Exmiaoshus;
                           expernews.Uptime = System.DateTime.Now;
                           expernews.Endtime = palyshow.EndTime;
                           expernews.Scheme = newsContents;
                           expernews.ColourMoney = nums;
                           expernews.ClickSum = 0;
                           expernews.ExperRemark = ExperRemarks;
                           expernews.CheckMsg = "0";
                           var addcount = ExpertNewsBLL.Add(expernews);
                           if (addcount > 0)
                           {
                               Context.Response.Write("1");
                           }
                           else
                           {
                               Context.Response.Write("数据库繁忙...请稍后！");
                           }

                       }
                       else
                       {
                           Context.Response.Write("期号时间有误，请联系客服!");
                       }
                    }
                    else
                    {
                        Context.Response.Write("您不是专家用户!");
                    }
                    

                }
            }
            else
            {
                Context.Response.Write("尚未登录!");//尚未登录
            }
        }
        void login_pmusers()
        {
             string textCode = HttpContext.Current.Request["textCode"];
            string checkCode = HttpContext.Current.Request.Cookies["yzmcode"].Value;
            //验证验证码
            if (textCode.Equals(checkCode, StringComparison.CurrentCultureIgnoreCase))
            {
                string username = HttpContext.Current.Request["tuserName"];
                string pwd = HttpContext.Current.Request["tuserpwd"];
                string randcode = HttpContext.Current.Request["trandcode"];
                UsersModel usermodel = UsersBLL.GetUsersInfo(username);
                if (usermodel.UserName != null)
                {
                    if (username.Equals(usermodel.UserName) && pwd.Equals(PasswordHelper.Md5(usermodel.UserPassword+randcode)))
                    {
                        if (usermodel.UserState == UserStateEnum.UnLogin)
                        {
                            Context.Response.Write("用户被禁用请联系管理员！");
                        }
                        else
                        {
                            AuthTicket(usermodel);
                            //存取用户信息
                            Context.Response.Write("1");
                        }
                    }
                    else
                    {
                        Context.Response.Write("0");
                    }
                }
                else
                {
                    Context.Response.Write(usermodel.UserPassword);
                }
                
            }
            

        }
        //写入验证票据, 
        /// <summary>
        ///  写入验证票据, 
        /// </summary>
        /// <param name="user"></param>
        private void AuthTicket(UsersModel user)
        {
       
         Context.Session[LoginUserUtil.LOGIN_USER] = user;//将用户 存入 session
            AuthenticationSection authentication =
                (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication");
            DateTime dt = DateTime.Now;
            FormsAuthenticationTicket fat = new FormsAuthenticationTicket(
                1, user.UserName, dt, dt.AddMinutes(
                    authentication.Forms.Timeout.TotalMinutes), false,
                string.Format("{0},{1},{2}",Context.Request.UserHostAddress, user.Id, user.UserName));
            string securityFat = FormsAuthentication.Encrypt(fat);

            HttpCookie hcLogin = new HttpCookie(FormsAuthentication.FormsCookieName) { Value = securityFat };
            Context.Response.Cookies.Add(hcLogin);
        }

        void UserName_pmusers()
        {
            string username = HttpContext.Current.Request["tuserName"];
            UsersModel usermodel = UsersBLL.GetUsersInfo(username);
            if (usermodel.UserName== null)
            {
                Context.Response.Write("0");
            }
            else
            {
                Context.Response.Write("1");
            }
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        void Add_pmusers()
        {
            UsersModel users = new UsersModel();
            string textCode = HttpContext.Current.Request["textCode"];
            string checkCode = HttpContext.Current.Request.Cookies["yzmcode"].Value;
            //验证验证码
            if (textCode.Equals(checkCode, StringComparison.CurrentCultureIgnoreCase))
            {
                users.UserName = HttpContext.Current.Request["tuserName"];
                users.TrueName = "";
                users.UserIntegral = 0; //积分
                string uspwd = HttpContext.Current.Request["tuserpwd"];
                users.UserPassword = uspwd; 
                users.UserEmail = HttpContext.Current.Request["tusersEmail"];
                users.UserEmailState = false;
                users.UserMobile = "";
                users.UserMobileState = false;
                users.UserQQ = HttpContext.Current.Request["tusersqq"];
                users.UserMSN = "";
                users.UserColourMoney = 0;   //彩币
                users.UserMoney = 0;
                users.UserLoginTime = System.DateTime.Now;
                users.UserRegisterTime = System.DateTime.Now;
                users.UserUpdateTime = System.DateTime.Now;
                users.UserImgUrl = "";
                users.UserState = Enums.Users.UserStateEnum.Normal;

                users.UserLoginState = false;//未登陆
                users.UserRemark = "";

                users.CreateTime = System.DateTime.Now;
                users.CreateUser = -2;
                users.LastModifyTime = System.DateTime.Now;
                users.LastModifyUser = -1;
                int userid = UsersBLL.Add(users);

                if (userid > 0)
                {
                    UAUserOfRoleModel usro = new UAUserOfRoleModel();
                    usro.UserID = userid;
                    usro.RoleID = 6;
                    usro.Status = 1;
                    usro.CreateUser = -1;
                    usro.CreateTime = System.DateTime.Now;
                    usro.LastModifyTime =System.DateTime.Now;
                    usro.LastModifyUser = -1;
                    int userofrole = UAUserOfRoleBLL.Add(usro);
                    if (userofrole > 0)
                    {
                        //存储注册用户名
                        Context.Response.Cookies.Add(new HttpCookie("LotteryuserNamevalue", users.UserName));
                        Context.Response.Write("1");
                    }
                    else
                    {
                        
                        Context.Response.Write("-1");
                    }
                }
                else
                {
                    Context.Response.Write("-1");
                }
            }
            else
            {
                Context.Response.Write("2");
            }

          

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}